var con = require('./connection');
var util = require('./util');
var _ = require('underscore');
var fs = require('fs');




/*查看数据库的说有表名*/
con.query("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'haorui_calc'", function (err, tableNames, fields) {
    _.each(tableNames, function (tableInfo, n) {
        var tableName = tableInfo.TABLE_NAME;
        con.query('SELECT * from ' + tableName, function (err, rows, fields) {
            if (err) {
                console.log('[query] - :' + err);
                return;
            }
            //写入文件
            var data = parseDataRow2ameRow(rows);
            fs.writeFile('./json/' + tableName + '.json', JSON.stringify(data), {
                flag: 'w',
                encoding: 'utf-8',
                mode: '0666'
            }, function (err) {
                if (err) {
                    console.log("文件写入失败", err)
                } else {
                    console.log("文件写入成功");
                    if (n == tableNames.length) {
                        endCon()
                    }
                }
            })


        });
    })
})



var endCon = function () {
    //关闭connection
    con.end(function (err) {
        if (err) {
            return;
        }
        console.log('[connection end] succeed!');
    });
}
var parseDataRow2ameRow = function (_array) {
    var _rows = [];
    _.each(_array, function (row) {
        var json = {};
        _.each(row, function (content, key) {
            json[util.data2ame(key)] = content;
        })
        _rows.push(json);
    })
    return _rows
}